Ok, I fixed it up for you. Some points to note:
1. I took out all your typecasts. Explicitly typecasting tells the compiler to shut up about warnings and this could sometimes hide errors in your code. In your case, it did. Your getX() routine happily converted an int* to an int and your setX() converted an int to an int* arbitrarily. Typecasting one type to another should be used very sparingly and only when you know what you're doing. This is why you weren't getting warnings, since you told the compiler to shut up by your typecasting.
2. Functions should be written as code. Function pointers, on the other hand, can be allocated on the heap. That is what I've done.
3. In C++, there is an invisible, implicit pointer to the object itself, called "this" which is automatically passed to all member functions of a class. So when you call obj->foo(5, 10), C++ actually calls foo(obj, 5, 10) when it compiles the code. Since this is C, we have to add this pointer ourselves and pass it ourselves as well. Hence, you'll see uses of test->getX(test) and test->setX(test, 5) and so on.
#include <stdio.h>
#include <stdlib.h>
typedef struct point {
int *myX;
int (*getX)(struct point *self);
void (*setX)(struct point *self, int x);
void (*die)(struct point *self);
} Point;
static int getX(Point *this)
{
return *(this->myX);
}
static void setX(Point *this, int x)
{
*(this->myX) = x;
}
static void die(Point *this)
{
free(this->myX);
free(this);
}
Point* NewPoint() {
//Put a new Point and x on the heap
Point* myPointer = (Point*) malloc(sizeof(Point));
if (!myPointer)
return NULL;
int* myX = malloc(sizeof(int));
if (!myX) {
free(myPointer);
return NULL;
}
myPointer->myX = myX;
//Assign the object its functions
myPointer->getX = getX;
myPointer->setX = setX;
myPointer->die = die;
//Return object
return myPointer;
}
int main() {
Point* test = NewPoint();
test->setX(test, 5);
printf("Point.x equals %d\n" , test->getX(test));
test->die(test);
return 0;
}
I will try out with my Ubuntu compiler at work tomorrow.